/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.proposeproduct.web.ProposeProductAction
   Module Description   :

   Date Created      : 2009/11/15
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.proposeproduct.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.proposeproduct.entity.ProposeProduct;
import com.yaodian100.ec.proposeproduct.entity.ProposeProductBatch;
import com.yaodian100.ec.proposeproduct.entity.ProposeSpecification;
import com.yaodian100.ec.proposeproduct.service.ProposeProductBatchService;
import com.yaodian100.ec.proposeproduct.service.ProposeProductService;
import com.yaodian100.ec.proposeproduct.service.ProposeSpecificationService;

/**
 * @author ellen.li 供应商提报
 */
public class ProposeProductAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private Menu prodTpMenu; // 與 getter, setter
	private static final long serialVersionUID = -4085923403825542258L;
	private final Logger logger = LoggerFactory.getLogger(ProposeProductAction.class);
	private DomainService<Menu> menuService; // 與 setter
	private ProposeSpecificationService proposeSpecificationService;

	private ProposeProductService proposeProductService;
	private ProposeProduct proposeProduct;
	private ProposeSpecification proposeSpecification;
	private ProposeProductBatchService proposeProductBatchService;
	private ProposeProductBatch proposeProductBatch;
	// private ImageService imageService;
	private String title;// 设置上传文件的标题

	private File upload;// 封装上传文件
	// private String uploadFileName;// 设置上传文件的文件名
	private String uploadContentType;// 上传文件的类型
	private String savePath;// 上传文件的保存路径
	private String rData = "";
	private String message;
	private final StringBuffer sbMessage = new StringBuffer();
	private StringBuffer filename;
	private String filenamePath = "";
	private String prpsPrdctBatchId;
	private Map<String, Object> resultList = new HashMap<String, Object>();
	private Hashtable<String, String> checkName;
	private List<ProposeProduct> products;
	private List<String> messageList;
	private int countTotal = 0;
	private List<List> previewList;
	private String editsupplier;
	private String editTwSupplier;// 台湾馆供应商

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	/*
	 * 取得供应商BatchID
	 */
	public String getBatchid() throws CoreException {
		proposeProductBatch = new ProposeProductBatch();
		proposeProductBatch.setFileCreateDate(new Date());
		proposeProductBatchService.save(proposeProductBatch);
		return proposeProductBatch.getId();
	}

	public int getCountTotal() {
		return countTotal;
	}

	public StringBuffer getFilename() {
		return filename;
	}

	/**
	 * @return the imageService
	 */
	// public ImageService getImageService() {
	// return imageService;
	// }

	public String getMessage() {
		return message;
	}

	public List<String> getMessageList() {
		return messageList;
	}

	public Menu getProdTpMenu() {
		return prodTpMenu;
	}

	public List<ProposeProduct> getProducts() {
		return products;
	}

	public ProposeProduct getProposeProduct() {
		return proposeProduct;
	}

	public ProposeProductBatch getProposeProductBatch() {
		return proposeProductBatch;
	}

	public ProposeProductBatchService getProposeProductBatchService() {
		return proposeProductBatchService;
	}

	public ProposeProductService getProposeProductService() {
		return proposeProductService;
	}

	public ProposeSpecification getProposeSpecification() {
		return proposeSpecification;
	}

	public ProposeSpecificationService getProposeSpecificationService() {
		return proposeSpecificationService;
	}

	/**
	 * @return the prpsPrdctBatchId
	 */
	public String getPrpsPrdctBatchId() {
		return prpsPrdctBatchId;
	}

	public String getrData() {
		return rData;
	}

	public Map<String, Object> getResultList() {
		return resultList;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public String getTitle() {
		return title;
	}

	public File getUpload() {
		return upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void prepare() throws Exception {
		messageList = new ArrayList();
		if (prodTpMenu == null) {
			prodTpMenu = menuService.get("Product.Type");
		}

		countTotal = 0;
		sbMessage.setLength(0);
	}

	public void setCountTotal(int countTotal) {
		this.countTotal = countTotal;
	}

	public void setFilename(StringBuffer filename) {
		this.filename = filename;
	}

	/**
	 * @param imageService the imageService to set
	 */
	// public void setImageService(ImageService imageService) {
	// this.imageService = imageService;
	// }

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void setMessageList(List<String> messageList) {
		this.messageList = messageList;
	}

	public void setProdTpMenu(Menu prodTpMenu) {
		this.prodTpMenu = prodTpMenu;
	}

	public void setProducts(List<ProposeProduct> products) {
		this.products = products;
	}

	public void setProposeProduct(ProposeProduct proposeProduct) {
		this.proposeProduct = proposeProduct;
	}

	public void setProposeProductBatch(ProposeProductBatch proposeProductBatch) {
		this.proposeProductBatch = proposeProductBatch;
	}

	public void setProposeProductBatchService(ProposeProductBatchService proposeProductBatchService) {
		this.proposeProductBatchService = proposeProductBatchService;
	}

	public void setProposeProductService(ProposeProductService proposeProductService) {
		this.proposeProductService = proposeProductService;
	}

	public void setProposeSpecification(ProposeSpecification proposeSpecification) {
		this.proposeSpecification = proposeSpecification;
	}

	public void setProposeSpecificationService(ProposeSpecificationService proposeSpecificationService) {
		this.proposeSpecificationService = proposeSpecificationService;
	}

	/**
	 * @param prpsPrdctBatchId the prpsPrdctBatchId to set
	 */
	public void setPrpsPrdctBatchId(String prpsPrdctBatchId) {
		this.prpsPrdctBatchId = prpsPrdctBatchId;
	}

	public void setrData(String rData) {
		this.rData = rData;
	}

	public void setResultList(Map<String, Object> resultList) {
		this.resultList = resultList;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	/**
	 * @return the editsupplier
	 */
	public String getEditsupplier() {
		return editsupplier;
	}

	/**
	 * @param editsupplier the editsupplier to set
	 */
	public void setEditsupplier(String editsupplier) {
		this.editsupplier = editsupplier;
	}

	/**
	 * @return the editTwSupplier
	 */
	public String getEditTwSupplier() {
		return editTwSupplier;
	}

	/**
	 * @param editTwSupplier the editTwSupplier to set
	 */
	public void setEditTwSupplier(String editTwSupplier) {
		this.editTwSupplier = editTwSupplier;
	}

	public String start() {
		return "start";
	}

	/**
	 * @return the filenamePath
	 */
	public String getFilenamePath() {
		return filenamePath;
	}

	/**
	 * @param filenamePath the filenamePath to set
	 */
	public void setFilenamePath(String filenamePath) {
		this.filenamePath = filenamePath;
	}

	/**
	 * @return the previewList
	 */
	public List<List> getPreviewList() {
		return previewList;
	}

	/**
	 * @param previewList the previewList to set
	 */
	public void setPreviewList(List<List> previewList) {
		this.previewList = previewList;
	}

	/*
	 * 更新供应商Batch档案名称栏位
	 */
	public void updateBatchFileName() throws CoreException {
		proposeProductBatch.setFileName(getFilename().toString());
		proposeProductBatchService.update(proposeProductBatch);
	}

	public void updatedList(String batchid) throws CoreException {
		CommonCriteria crit = new CommonCriteria();
		if (StringUtils.isNotBlank(batchid)) {
			crit.addEq("proposeProductBatchId", batchid);
		}
		products = proposeProductService.getList(0, -1, crit, null);
	}

	/**
	 * 預覽excel
	 * 
	 * @return
	 * @throws Exception
	 */
	public String preview() throws Exception {
		List<List> excelLists = new ArrayList();
		/* 新增一笔至ProposeProductBatch */
		filename = new StringBuffer();
		filename.append(ServerValue.getMidApachePath()).append(File.separator).append("upldprodxml").append(File.separator);
		// checkName = new Hashtable();// 确认下一笔名称是否相同
		// prpsPrdctBatchId = getBatchid();
		// filename.append(prpsPrdctBatchId).append(".xls");
		filename.append(new Date().getTime()).append(".xls");
		// updateBatchFileName();// update file path to file_name field
		/* 复制并更名xls至server */
		FileUtils.copyFile(getUpload(), new File(filename.toString()));
		InputStream inp = new FileInputStream(getUpload());

		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);

		excelLists = excelToList(sheet);
		setEditsupplier(editsupplier);
		setEditTwSupplier(editTwSupplier);
		inp.close();
		countTotal = excelLists.size();
		previewList = new ArrayList<List>(excelLists);
		return "previewExcel";
	}

	/**
	 * @param sheet
	 * @return
	 */
	private List<List> excelToList(Sheet sheet) {
		List<List> excelLists = new ArrayList();

		Cell cell = null;
		int size = 2;
		try {
			for (int i = 2; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				if (null != row) {
					cell = row.getCell(0);
					if (null != cell && StringUtils.isNotBlank(cell.toString())) {
						size++;
					}
				}
			}
			for (int i = 2; i < size; i++) {
				Row row = sheet.getRow(i);
				if (row != null) {
					List<String> list = new ArrayList<String>();
					cell = row.getCell(0);
					if (null == cell || StringUtils.isBlank(cell.toString())) {
						// logger.info("無商品名稱");
					} else {
						for (int j = 0; j < 45; j++) {
							cell = row.getCell(j);
							if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
								try {
									if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
										list.add(cell.getStringCellValue().trim());
									} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
										BigDecimal iii = new BigDecimal(cell.getNumericCellValue());
										DecimalFormat df = new DecimalFormat("#######.##");
										list.add(df.format(cell.getNumericCellValue()));
									} else {
										list.add(cell.getStringCellValue().trim());
									}
								} catch (Exception ee) {
									
									list.add(cell.getStringCellValue().trim());
								}
							} else {
								list.add("");
							}
						}
					}
					if (list.size() > 0) {
						excelLists.add(list);
					}
				}

			}
		} catch (Exception e) {
			
		}
		return excelLists;
	}

	/**
	 * 預覽後上傳
	 * 
	 * @return
	 * @throws Exception
	 */
	public String uploadAndSave() throws Exception {
		List<List> excelLists = new ArrayList<List>();
		InputStream inp = new FileInputStream(filenamePath);
		prpsPrdctBatchId = getBatchid();
		setFilename(new StringBuffer(filenamePath));
		updateBatchFileName();

		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);

		excelLists = excelToList(sheet);
		inp.close();
		resultList = proposeProductService.uploadExcelAndSaveAsProduct(excelLists, prpsPrdctBatchId, getEditsupplier(),
				getEditTwSupplier());
		countTotal = Integer.parseInt(resultList.get("countTotal").toString());
		updatedList(proposeProductBatch.getId());
		return "finish";
	}

	/*
	 * 上传档案
	 */
	public String upload() throws Exception {
		List excelLists = new ArrayList();
		/* 新增一笔至ProposeProductBatch */
		filename = new StringBuffer();
		filename.append(ServerValue.getMidApachePath()).append(File.separator).append("upldprodxml").append(File.separator);
		checkName = new Hashtable();// 确认下一笔名称是否相同
		prpsPrdctBatchId = getBatchid();
		filename.append(prpsPrdctBatchId).append(".xls");
		updateBatchFileName();// update file path to file_name field
		/* 复制并更名xls至server */
		FileUtils.copyFile(getUpload(), new File(filename.toString()));
		InputStream inp = new FileInputStream(getUpload());
		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);
		Cell cell = null;
		int size = 2;
		try {
			for (int i = 2; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				if (null != row) {
					cell = row.getCell(0);
					if (null != cell && StringUtils.isNotBlank(cell.toString())) {
						size++;
					}
				}
			}
			for (int i = 2; i < size; i++) {
				Row row = sheet.getRow(i);
				if (row != null) {
					List<String> list = new ArrayList<String>();
					cell = row.getCell(0);
					if (null == cell || StringUtils.isBlank(cell.toString())) {
						logger.info("無商品名稱");
					} else {
						for (int j = 0; j < 48; j++) {
							cell = row.getCell(j);
							if (cell != null) {
								try {
									if (cell.getCellType() == cell.CELL_TYPE_STRING || cell.getCellType() == cell.CELL_TYPE_BLANK) {
										list.add(cell.getStringCellValue().trim());
									} else {
										BigDecimal iii = new BigDecimal(cell.getNumericCellValue());
										list.add(iii.toString());
									}
								} catch (Exception ee) {
									list.add(cell.getStringCellValue().trim());
								}
							} else {
								list.add("@");
							}
						}
					}
					if (list.size() > 0) {
						excelLists.add(list);
					}
				}

			}
		} catch (Exception e) {
			logger.info("exception:{}", e.getMessage());
		}
		inp.close();
		resultList = proposeProductService.uploadExcel(excelLists, prpsPrdctBatchId);
		countTotal = Integer.parseInt(resultList.get("countTotal").toString());
		updatedList(proposeProductBatch.getId());
		return "finish";
	}

}
